#include "gridwidget.h"
#include <QPainter>
#include <QMouseEvent>
#include <QRect>
#include "world.h"

GridWidget::GridWidget(QWidget *parent) :
    QWidget(parent), m_row(20), m_col(20), m_world(NULL)
{
    m_cells.clear();
    setFixedSize(400, 400);
    m_world = new World(m_row, m_col);

    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(stepWorld()));
}

GridWidget::~GridWidget() {
    delete m_world;
}

void GridWidget::toggleTimer(bool isRun) {
    if (!isRun) {
        m_timer->stop();
    } else {
        m_timer->start(1000);
    }
}

void GridWidget::stepWorld() {
    m_world->step();
    repaint();
}

void GridWidget::paintEvent(QPaintEvent *) {
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(QPen(Qt::darkGreen, 1));
    for (int i = 0; i <= width() / getCellSize(); ++i) {
        painter.drawLine(i * getCellSize(), 0, i * getCellSize(), height());
    }
    for (int i = 0; i <= height() / getCellSize(); ++i) {
        painter.drawLine(0, i * getCellSize(), width(), i * getCellSize());
    }

    painter.setBrush(QBrush(Qt::cyan, Qt::SolidPattern));
    const CellContainer& cc = m_world->getActiveCells();
    for (CellContainer::const_iterator b = cc.begin(), e = cc.end(); b != e; ++b) {
        CellId cell = *b;
        painter.drawRect(cellRect(cell.first, cell.second));
    }

}

void GridWidget::mousePressEvent(QMouseEvent *event)
{
    int row = event->pos().x() / getCellSize();
    int col = event->pos().y() / getCellSize();
//    m_cells.push_back(std::make_pair(row, col));
    m_world->reverseCellStatus(row, col);
    repaint();
}


QRect GridWidget::cellRect(int row, int column) const
{
    return QRect(row * getCellSize(),
                 column * getCellSize() ,
                 getCellSize(),
                 getCellSize());
}
